package com.audaque.springboot.foshanupload.jwtcore.serializer;


import com.audaque.springboot.foshanupload.jwtcore.component.RsaUtilExtProvider;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Objects;

/**
 * @author zgb
 * @desc ...
 * @date 2022-11-23 15:35:05
 */
@Slf4j
public class RsaSerializer extends StdSerializer<Object> {



    private final Boolean enOrde;

    public RsaSerializer() {
        super(String.class, false);
        this.enOrde = null;
    }
    public RsaSerializer(boolean enOrde) {
        super(String.class, false);
        this.enOrde = enOrde;
    }


    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (Objects.isNull(value)) {
            return;
        }
        String str = value.toString();
        String base64Content = "";
        try {
            if(enOrde){
                base64Content=  RsaUtilExtProvider.encode(str);
            }else{
                base64Content=  RsaUtilExtProvider.decode(str);
            }


            gen.writeString(base64Content);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
